<template>
  <div>
    <p>注册页面</p>
    <!-- validate-first:校验失败后不再继续校验 -->
    <van-form validate-first @failed="onFailed">
      <!-- 通过 pattern 进行正则校验 -->
      <van-field
        v-model="formInfo.phone"
        name="validator1"
        placeholder="手机号"
        :rules="[
          {
            validator: validator1,
            required: true,
            message: '请输入正确内容',
            trigger: 'onBlur',
          },
        ]"
      />
      <van-field
        v-model="formInfo.nickname"
        placeholder="昵称"
        :rules="[
          { required: true, message: '请输入正确内容', trigger: 'onBlur' },
        ]"
      />
      <van-field
        v-model="formInfo.password"
        name="validator2"
        placeholder="密码"
        :rules="[
          {
            validator: validator2,
            required: true,
            message: '请输入正确内容',
            trigger: 'onBlur',
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          @click="submitForm"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formInfo: {
        phone: 1,
        nickname: "",
        password: 1,
      },
      // // 11位数字
      // pattern1: /\d{11}/,
      // // 6位数字
      // pattern2: /\d{6}/,
    };
  },
  methods: {
    // 提交表单
    submitForm() {
      let res1 = this.validator1(this.formInfo.phone);
      let res2 = this.validator2(this.formInfo.password);
      if (res1 && res2) {
        // 校验成功
        this.$http
          .post("/register", this.formInfo)
          .then((res) => {
            // 显示后台返回的信息
            this.$toast(res.msg);
            if (res.code === 200){
              // 注册成功
              this.$router.push('/login')
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        // 校验失败
        this.onFailed();
      }
    },
    // 校验函数返回 true 表示校验通过，false 表示不通过
    validator1(val) {
      console.log(val);
      // 校验手机号
      return /\d{11}/.test(val);
    },
    // 检验密码，6位数字
    validator2(val) {
      console.log(val);
      return /\d{6}/.test(val);
    },
    onFailed() {
      this.$toast("填写有误！");
    },
  },
};
</script>

<style>
</style>